﻿#include "mydelegate.h"
#include <QApplication>
#include <QPainter>
MyComboxDelegate::MyComboxDelegate(QObject *parent)
{

}

MyComboxDelegate::~MyComboxDelegate()
{

}

void MyComboxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
     editor->setGeometry(option.rect);
}

QSize MyComboxDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QSize size = QStyledItemDelegate::sizeHint(option, index);
    size.setHeight(70);
    return size;
}

ColorDelegate::ColorDelegate(QObject *parent)
{

}

ColorDelegate::~ColorDelegate()
{

}

void ColorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    auto text = index.data().toString();
    auto myOpt = option;
    myOpt.displayAlignment = Qt::AlignCenter;
    auto sWidth = myOpt.fontMetrics.width(text);
    auto sHeight = myOpt.fontMetrics.height();
    // 计算文字所在的范围，因为是居中对齐，所以需要计算相应的起始位置
    auto sRect = QRectF(myOpt.rect.x() + (myOpt.rect.width() - sWidth) / 2.0,
    myOpt.rect.y() + ((myOpt.rect.height() - sHeight) / 2.0), sWidth, sHeight);
    // 将渐变填充的范围设置成文字所在的范围
    QLinearGradient l(sRect.x(), sRect.y(), sRect.x() + sRect.width(),
    sRect.y() + sRect.height());
    // 设置彩虹色渐变效果，彩虹由赤橙黄绿青蓝紫的颜色组成
    // 因此我们除去起始点为红色，每隔1/6就设置一种颜色
    l.setColorAt(0, Qt::red);
    l.setColorAt(1.0 / 6, QColor(255, 97, 0));
    l.setColorAt(2.0 / 6, QColor(255, 255, 0));
    l.setColorAt(3.0 / 6, Qt::green);
    l.setColorAt(4.0 / 6, Qt::cyan);
    l.setColorAt(5.0 / 6, Qt::blue);
    l.setColorAt(1, QColor(255, 0, 255));
    // 这里并不使用painter，只需要QStyle即可实现效果
    // QPalette::Text为文本显示效果的role
    auto role = QPalette::Text;
    if (option.state & QStyle::State_Selected) {
    // 当前item被选中时绘制高亮的选中框
    role = QPalette::HighlightedText;
    painter->fillRect(option.rect, option.palette.highlight());
    }
    myOpt.palette.setBrush(role, QBrush(l));
    // 注意最后一个参数role，只有设置了它才能让QStyle正确地绘制自定义的文本显示效果
    QApplication::style()->drawItemText(painter, myOpt.rect, myOpt.displayAlignment,
    myOpt.palette, true, text, role);
}

QSize ColorDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    auto text = index.data().toString();
    auto width = option.fontMetrics.width(text) + 20;
    return QSize{width, option.fontMetrics.height()};
}
